<?php
/**
 * Created by PhpStorm.
 * User: Tsang
 * Date: 2017/9/24 16:20
 *
 */

namespace app\api\model;


use think\Model;

class Member extends Model
{

    /**
     * 获取用户信息
     * @param $original
     * @return array
     */
    public function getUser($original)
    {
        $openid = $original['original']['wx_openid'];
        $userData = $this->getByOpenID($openid);
        $result = [];
        if (empty($userData)){
            $resultData = $this->createUser($original['original']);
            $userData = db('member')->where(['id'=>$resultData])->find();
        }else{
            $resultData = $this->updateUser($userData['id'],$original['original']);
        }

        $result['user'] = $userData;
        return $result;
    }

    /**
    * api获取用户信心
    *
    *
    */
    public function getUserInfo($user_id)
    {
        $user = Member::get($user_id);
        return $user;
    }

    /**
     * 微信openid对应的用户是否存在
     * 存在返回uid，不存在返回0
     */
    public static function getByOpenID($openid)
    {
        $user = Member::where('wx_openid', '=', $openid)->find();
        if(empty($user)){
            return [];
        }
        $member = $user->toArray();
        unset($member['passwd']);
        return $member;
    }

    /**
     * 根据id获取用户信息
     * @param $uid
     * @return array
     *
     */
    public static function getByUID($uid)
    {
        $user = Member::where('id', '=', $uid)
            ->find();
        if(empty($user)){
            return [];
        }
        $member = $user->toArray();
        unset($member['passwd']);
        return $member;
    }

    /**
     * 创建用户
     * @param $original
     * @return mixed
     */
    private function createUser($original)
    {
        $original['create_time'] = time();
        $user = Member::create($this->dataFormat($original));
        $uid = $user->id;
        if ($uid == 0)return array('message'=>'授权登录失败','type'=>'create');
        $hxs = $this->hxcreateUser($user->id);
        // if(!$hxs){
        //     //假如环信注册失败
        //     db('member')->where(['id'=>$user->id])->delete();
        //     return array('message'=>'授权登录失败,请致电平台商了解!','type'=>'create');
        // }
        $hx['hx_username'] = $hxs['hxtoken']['entities'][0]['username'];
        $hx['hx_passwd'] = '123456';

        $im = $this->imcreateUser($user->id);
        if(empty($im)){
            $hx['im_username'] = $im['imidentifier'];
        }
        Member::where('id',$uid)->update($hx);
        return $user->id;
    }

    //注册环信
    public function hxcreateUser($uid)
    {
        $data = db('member')->where('id='.$uid)->find();
        $username = $uid.'_'.time();
        $password = '123456';
        $nickname = $data['nickname'];
        $easemob = new \app\api\service\Easemob();
        $result = $easemob->createUser($username,$password,$nickname);

        //file_put_contents('text.txt',$result);die;
        //$result = json_decode($result);
        $array_hxtoken['hxtoken'] = $result;
        return $array_hxtoken;

        // if(isset($result['entities'])){
        //     $array_hxtoken['hxtoken'] = $result;
        //     return $array_hxtoken;
        // }else{
        //     return false;
        // }
    }

    //腾讯im用户导入
    public function imcreateUser($uid)
    {
        $data = db('member')->where('id='.$uid)->find();
        $txIm = new \app\api\logic\Test();
        $identifier= $uid.'im'.time();
        $nick = $data['nickname'];
        $face_url = $data['headimage'];
        $restIm = $txIm->accountImport($identifier, $nick, $face_url);
        if($restIm['ActionStatus'] != 'OK')return ['message'=>'添加失败!'];
        $result['imidentifier']=$identifier;
        return $result;
    }

    /**
     * @param $original
     * @return mixed
     */
    private function dataFormat($original)
    {
        $data = [];
        foreach ($original as $k=>$v){
            if($v != "") $data[$k] = $v;
        }
        return $data;
    }

    /**
     * 更新用户
     * @param $root
     * @param $code
     * @return \think\response\Json
     */
    public function updateUser($uid,$original)
    {
        $affectedRows =  db('member')->where('id',$uid)
            ->update($this->dataFormat($original));
        if ($affectedRows == 0)
            return array('message'=>'更新用户信息失败','type'=>'update');
    }

}